<template>
  <div class="fx-table">
    <table>
      <tr>
        <th v-for="item in tableHeader" :key="item.prop">
          {{ item.label }}
        </th>
      </tr>
      <tr v-for="(item,index) in data" :key="index">
        <td v-for="child in tableHeader" :key="child.prop">
          {{ item[child.prop] ?? '-' }}
        </td>
      </tr>
    </table>
  </div>
  <slot></slot>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, onBeforeUnmount, PropType, provide, ref } from 'vue'
import mitt, { Emitter } from 'mitt'

type TableItemData = { label: string; prop: string }

export default defineComponent({
  name: 'fxTable',
  props: {
    data: {
      type: Array as PropType<unknown[]>,
      default: () => []
    }
  },
  setup () {
    const tableMitt: Emitter = mitt()
    const tableHeader = ref<TableItemData[]>([])

    provide<Emitter['emit']>('tableMittEmit', tableMitt.emit)

    const handleTableHeader = (header: TableItemData | undefined) => {
      if (!header) return
      tableHeader.value.push(header)
    }

    onBeforeMount(() => {
      tableMitt.on<TableItemData | undefined>('handleTableHeader', handleTableHeader)
    })

    onBeforeUnmount(() => {
      tableMitt.off('handleTableHeader', handleTableHeader)
    })

    return {
      tableHeader
    }
  }
})
</script>
